<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <title>家庭药品管理</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <link rel="stylesheet" href="static/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
    <style>
        .header-form-group {
            display: flex;
            flex-direction: row;
            justify-items: flex-start;
        }

        #get {
            display: flex;
            flex-direction: column;
        }
    </style>

    </head>
    <body>
        <div class="container" id="app">
            <div class="row">
                <nav class="navbar navbar-expand-lg navbar-light">
                    <a class="navbar-brand" href="#">首页</a>
                      <ul class="navbar-nav">
                        <li class="nav-item">
                          <a class="nav-link" v-on:click="reset_form()" data-target="#exampleModal" data-toggle="modal" href="#add" active>添加</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" v-on:click="fetch_data()" href="#" active>刷新( {{ countDown }}s后自动刷新)</a>
                        </li>
                      </ul>
                  </nav>
            </div>
            <div id="get">
                    <div class="header-form-group">
                        <label class="col-form-label" style="margin-right:10px">搜索</label>
                        <div style="margin-right:30px">
                            <input type="text" v-model="searchName"  class="form-control" id="name" value="">
                        </div>
                        <div>
                                load: {{load_avg.one}}, {{load_avg.five}}, {{load_avg.fifteen}} 温度: {{temperature}}℃ 
                        </div>
                        <div style="margin-left:10px">
                            <label> 展示用完的 </label>
                            <input type="checkbox" v-on:click="refresh_data()" id="checkbox" v-model="showZero" />
                        </div>

                    </div>
                <div class="row">
                    <table id="medicinesTable" class="table table-hover">
                        <thead>
                          <tr>
                            <th scope="col">ID</th>
                            <th scope="col">名称</th>
                            <th scope="col">数量</th>
                            <th scope="col">位置</th>
                            <th scope="col">已过期</th>
                            <th scope="col">功效</th>
                            <th scope="col"> </th>
                          </tr>
                        </thead>
                        <tbody>

                          <tr v-for="m in medicines">
                            <td>{{m.id}}</td>
                            <td>{{m.name}}</td>
                            <td>{{m.quantity}}</td>
                            <td>{{m.location}}</td>
                            <td v-if='m.expired' bgcolor='yellow' class="text-danger">{{m.expired}}</td>
                            <td v-else class='text-success'>{{m.expired}}</td>
                            <td><textarea readonly=true>{{m.usage}}</textarea></td>
                            <td><a href='#' v-on:click="edit(m.id)">编辑</a> </td>
                          </tr>
                        </tbody>
                      </table>
                </div>
            </div>
			<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
			  <div class="modal-dialog" role="document">
				<div class="modal-content">
				  <div class="modal-header">
					<h5 class="modal-title" id="add">添加</h5>
					<button type="button" class="close" data-dismiss="modal" aria-label="Close">
					  <span aria-hidden="true">&times;</span>
					</button>
				  </div>

                <div class="modal-body">
                    <form class="form" @submit.prevent="submit">
                        <div class="form-group row">
                            <label class="col-5 col-form-label">名称</label>
                            <div class="col">
                                <input v-model="form.name" type="text" class="form-control" id="name" value="">
                            </div>
                        </div>
                        <div class="form-group row">
                            <label class="col-5 col-form-label">生产日期</label>
                            <div class="col">
                                <input v-model="form.made_date" type="datetime" class="form-control" id="create_date" value="" placeholder="2019-01-01">
                            </div>
                        </div>
                        <div class="form-group row">
                            <label class="col-5 col-form-label">价格</label>
                            <div class="col">
                                <input v-model="form.price" type="number" class="form-control" id="price" value="">
                            </div>
                        </div>
                        <div class="form-group row">
                            <label class="col-5 col-form-label">有效期</label>
                            <div class="col">
                                <input v-model="form.effect_months" type="number" class="form-control" id="effect_mounts" value="" placeholder='月数'>
                            </div>
                        </div>
                        <div class="form-group row">
                        <label class="col-5 col-form-label">数量</label>
                            <div class="col">
                                <input v-model="form.quantity" type="number" class="form-control" id="quantity" value="">
                            </div>
                        </div>
                        <div class="form-group row">
                            <label class="col-5 col-form-label">功效</label>
                                <div class="col">
                                    <textarea rows=2 v-model="form.usage" class="form-control" id="usage" value=""></textarea>
                                </div>
                            </div>
                        <div class="form-group row">
                            <label class="col-5 col-form-label">位置</label>
                                <div class="col">
                                    <select v-model="form.location" class="form-control" id="location" value="">
                                            <option>公司</option>
                                            <option>家</option>
                                            <option>丢弃</option>
                                        </select>
                                </div>
                            </div>
                        <div class="form-group row">
                            <label class="col-5 col-form-label">购买途径</label>
                                <div class="col">
                                    <input v-model="form.bought_from" type="text" class="form-control" id="bought_from" value="西丽医院">
                                </div>
                            </div>
                        <div class="form-group row">
                            <label class="col-5 col-form-label">购买日期</label>
                            <div class="col">
                                <input v-model="form.bought_date" type="datetime" class="form-control" id="bought_date" value="" placeholder="2019-01-01">
                            </div>
                        </div>
                        <div class="form-group row">
                            <label class="col-5 col-form-label">品牌</label>
                                <div class="col">
                                    <input v-model="form.brand" type="text" class="form-control" id="brand" value=" ">
                                </div>
                            </div>
                        <div class="modal-footer">
							<button id="closeButton" type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                            <button type="submit" class="btn btn-primary">提交</button>
                            <div class="alert alert-dismissible fade true" v-bind:class="{ show: alertShow, hide: !alertShow, 'alert-success': !hasError, 'alert-danger': hasError }" role="alert">
                                <p class="alert-res">{{alertMessage}}</p>
                                <button v-on:click="closeAlert()" type="button" class="close" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                        </div>
                      </form>
                </div>
            </div>
        </div>
	</div>
 </div>
        <script src="static/vue2.js"></script>
        <script src="static/axios.min.js"></script>
		<script src="static/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
        <script src="static/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
		<script src="static/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
        <!-- vue -->
        <script>
            var app = new Vue({
                el: '#app',
                data: {
                    form: {},
                    load_avg: {
                        one: 0.1,
                    },
                    temperature: 0,
                    searchName: '',
                    allMedicines: [],
                    medicines: [],
                    alertShow: false,
                    alertMessage: '',
                    countDown: 10,
                    showZero: false,
                    hasError: false,
              
                },
                watch: {
                    searchName: "searchNameUpdated",
                    },
                mounted: function() {
                    this.allMedicines = this.medicines;
                    this.fetch_data();
                    this.fetch_status();
                    this.timer = setInterval(this.count_down, 1000);
                    this.countDown = 10;
                    this.showZero = true;
                },
                methods: {
                    count_down: function() {
                        if (this.countDown == 0) {
                            // this.fetch_data(); 更新数据会导致对方框中内容被刷掉。
                            this.fetch_status();
                            this.countDown = 10;
                            return;
                        }
                        this.countDown = this.countDown - 1;
                    },
                    fetch_data: function() {
                        axios.get('/api/v1/medicines').then(res => {
                            this.allMedicines = res.data;
                            this.medicines = this.allMedicines;
                            if (!this.showZero) {
                                this.medicines = this.medicines.filter(med => med.quantity > 0 && !med.expired);
                            } 
                            this.form = {};
                        });
                    },
                    fetch_status: function() {
                        axios.get('/status').then(res => {
                            this.load_avg = res.data.load_avg;
                            this.temperature = res.data.temperature;
                        });
                    },
                    refresh_data: function() {
                            this.medicines = this.allMedicines;
                            if (this.showZero) {
                                this.medicines = this.medicines.filter(med => med.quantity > 0 && !med.expired);
                            } 
                            this.form = {};
                    },
                    reset_form: function() {
                        this.form = {};
                    },
                    edit: function(e) {
                        id = e;
                        for (i = 0; i < this.allMedicines.length; i++) {
                            var med = this.allMedicines[i];
                            if (id == med.id) {
                                this.form = med;
                                break;
                            }
                        }
                        var myModal = new bootstrap.Modal(document.getElementById('exampleModal'));
                        myModal.show();
                    },
                    closeAlert: function() {
                        this.alertShow = false;
                    },
                    submit: function() {
                        axios.defaults.headers.post['Content-Type'] = 'application/json; charset=UTF-8';
                        if (this.form.name === "") {
                            return;
                        }
                        data = this.form
                        data.price = parseFloat(data.price);
                        if (data.id == undefined)
                            data.id = 0;
                        data.expired = false;
                        data.quantity = parseInt(data.quantity);
                        data.effect_months = parseInt(data.effect_months);
                        axios.post('/api/v1/medicine', data,
                                    ).then(res => {
                                        this.hasError = false;
                                        this.alertMessage = "操作成功";
                                        this.alertShow = true;
                                        setTimeout(() => {
                                            this.alertShow = false;
                                            $("#closeButton").click();
                                        }, 1000);
                                        this.fetch_data();
                                    }).catch(err => {
                                        this.hasError = true;
                                        this.alertMessage = "操作失败";
                                        this.alertShow = true;
                                        setTimeout(() => {
                                            this.alertShow = false;
                                        }, 1000);
                                    });
                    },
                    searchNameUpdated: function(newVal, oldVal) {
                        if (this.searchName === '') {
                            this.medicines = this.allMedicines;
                        } else {
                            this.medicines = this.allMedicines.filter(med => med.name.search(this.searchName) >= 0 || med.usage.search(this.searchName) >= 0);
                        }
                    },
                }
            });
        </script>
    </body>

</html>
